//引入工具模板
const Koa = require('koa');
const app = new Koa();
const router = require('koa-router')();
const bodyparser = require("koa-bodyparser")
const cors = require('koa-cors')

const { Sequelize, Op, DataTypes } = require('sequelize');






//数据库
const sequelize = new Sequelize('text', 'postgres', 'zyfyyds', {
    host: 'zyfyyds.top',
    dialect: 'postgres'
})

let Blog = sequelize.define('blog', {
    tite: {
        type: DataTypes.STRING,
        allowNull: false
    },
    imports: {
        type: DataTypes.STRING,
        allowNull: false
    },
    text: {
        type: DataTypes.STRING,
        allowNull: false
    }

})


    //查找和展示数据
    router.get('/blog', async(ctx, next) => {
            let keyword = ctx.request.query.obj;
            console.log(keyword);
            if (keyword != '') { 
                ctx.body = await Blog.findAll({
                    where: {
                        [Op.or]: [
                            { id: isNaN(keyword) ? -1 : parseInt(keyword) },

                            { tite:{[Op.like]:'%'+ keyword +'%'}},
                            { imports:{[Op.like]:'%'+ keyword +'%'}},
                            { text: {[Op.like]:'%'+ keyword +'%'} }
                        ]
                    },
                    order: ['id']
                })
            } else {
                ctx.body = await Blog.findAll({ order: ['id'] })
            }
        })
    //删除
    router.delete('/blog', async(ctx, next) => {
            let id = ctx.request.body.obj;
            console.log(id);
            await Blog.destroy({ where: { id: id } })
            ctx.body = await Blog.findAll({ order: ['id'] });

        })
    //修改
    router.put('/blog', async(ctx, next) => {
            let obj = ctx.request.body;
            console.log(obj, 333);
            if (obj.id) {
                await Blog.update(obj, { where: { id: obj.id } })
                ctx.body = await Blog.findAll({ order: ['id'] });
            }
        })
    //添加
    router.post('/blog', async(ctx, next) => {
        let obj = ctx.request.body;
        console.log(obj, 555);
        await Blog.create(obj)
        ctx.body = await Blog.findAll({ order: ['id'] });
    })

    //挂载工具
    app.use(cors());
    app.use(bodyparser())
    app.use(router.routes())

    //监听

    app.listen(8000, () => {
        console.log(`http://localhost:8000`);
    })